﻿#pragma once
#include "AppDelegate.h"
#include "WStringSupport.h"
#include "SceneMusicSelect.h"
#include "SceneFallingSingle.h"
#include "SceneMainMenu.h"
#include "StringTools.h"
#include <thread>

#define random_r RandomHelper::random_real

USING_NS_CC;

Scene* SceneMusicSelect::createScene()
{
	auto scene = Scene::create();
	auto layer = SceneMusicSelect::create();
	layer->setAnchorPoint(Point(0.5, 0.5));
	scene->addChild(layer);

	return scene;
}

bool SceneMusicSelect::init()
{
	if (!Layer::init())
	{
		return false;
	}
	UI::setWndTItle(L"Music Select");
	addChild(LayerColor::create(Color4B::WHITE));
	createBG();
	createUI();
	playBGM();
	sceneFadeInEffect();
	scheduleUpdate();

	auto testlabel = Label::createWithTTF("Preview version.", FONTA, 32);
	UI::setNodeAnch(testlabel, ANCH_TL);
	testlabel->setPosition(0, frameSize.height);
	addChild(testlabel, 65535);

	auto uiss = UISceneSwitcher::create(UISS_MODE(sceneSwitchMode), ENTER);
	addChild(uiss);
	uiss->play();

	return true;
}

void SceneMusicSelect::createBG()
{
	mscover = MusicSelectCover::create(frameSize, 0, pNotemgr->bgFile);
	addChild(mscover);
	//mscover->additionalEventActions.onMouseDown = CC_CALLBACK_0(SceneMusicSelect::gotoSoloScene, this);
}

void SceneMusicSelect::createUI()
{
	topbar = MusicSelectUITitle::create();
	addChild(topbar, 100);
	for (int i = 0; i < 6; i++)
	{
		string name = "";
		function<void()> eventFunc = nullptr;
		switch (i)
		{
			case 0:name = "EXIT"; break;
			case 1:name = "BACK"; eventFunc = CC_CALLBACK_0(SceneMusicSelect::backtoMainmenu, this); break;
			case 2:
				name = "SETTING";
				eventFunc = [&]
				{
					auto setting = UISetting::create(UI::moveEventFlagUp());
					setting->setPositionY(-frameSize.height);
					addChild(setting, 200);
					setting->runAction(EaseQuarticActionOut::create(MoveTo::create(.2f, Vec2::ZERO)));
				};
				break;
			case 3:name = "FRIENDS"; break;
			case 4:name = "LOBBY"; break;
			case 5:name = "PLAY"; break;
			default:break;
		}
		if (eventFunc == nullptr) topbar->addButton(name);
		else topbar->addButton(name, eventFunc);
	}
	topbar->setActiveBtn(5);
	createConsolePanel();
	listArea = Size(frameSize.width*0.25f, frameSize.height - topbar->getContentSize().height - msconsole->getContentSize().height);
	createList();
	createInfoPanel();
	auto startarea = MusicSelectGotoPlayScene::create(
		Size(
			frameSize.width - listArea.width * 2,
			frameSize.height - topbar->getContentSize().height - msconsole->getContentSize().height
		)
	);
	startarea->setPosition(listArea.width, msconsole->getContentSize().height);
	startarea->setAdditionalEventAction(EventHelper::MouseEventType::MOUSEDOWN, CC_CALLBACK_0(SceneMusicSelect::gotoSoloScene, this));
	addChild(startarea);
}

void SceneMusicSelect::createList()
{
	listmgr.loadAll();
	auto listContainer = LayerColor::create(THEMECOLORBA(0), listArea.width, listArea.height);
	listContainer->setPositionY(msconsole->getContentSize().height);
	addChild(listContainer);
	mlist = MusicList::create(Vec2::ZERO, listArea, listArea.height / 10.5, &listmgr, &levelmgr);
	listContainer->addChild(mlist);
	mlist->setAdditionalEventAction(EventHelper::MOUSEUP, CC_CALLBACK_0(SceneMusicSelect::changeMusicSelect, this));
	auto currentitem = (MusicListItem*)mlist->getChildByName(strtool::int2str(pNotemgr->setId));
	auto index = currentitem->getTag();
	mlist->hoverindex = index;
	mlist->selectedindex = index;
	mlist->selectedItem = mlist->getItemByIndex(index);
	mlist->openLevelList();
	currentitem->hover();
	currentitem->selected();
}

void SceneMusicSelect::createConsolePanel()
{
	auto consoleSize = Size(frameSize.width, 125);
	msconsole = MusicSelectConsole::create(Size(consoleSize));
	addChild(msconsole, 100);
}

void SceneMusicSelect::createInfoPanel()
{
	auto infoSize = listArea;
	msinfopanel = UIMusicInfoPanel::create(infoSize, infoSize.width*.1f);
	msinfopanel->setPosition(frameSize.width - infoSize.width, msconsole->getContentSize().height);
	addChild(msinfopanel);

	auto page0 = msinfopanel->addTabPage("Map Info", 1, 1);
	msinfopanel->setTabButtonActive(0);
	mapinfo = MusicSelectInfo::create(msinfopanel->pagearea);
	mapinfo->setInfoValue(mlist->levelmgr, mlist->selectedLevelIndex, pNotemgr);
	page0->addItem(mapinfo, 1, 1);

	msinfopanel->addTabPage("My Record", 1, 10, true);
}

void SceneMusicSelect::playBGM()
{
	bool isbgmplaying;
	pAudioSystem->curbgm.pChl->isPlaying(&isbgmplaying);
	string previewFile = pNotemgr->getPreviewFileName();
	if (!isbgmplaying && !previewFile.empty()) pAudioSystem->playBGMFadeIn(previewFile, 1000, VOLUMEMUSIC, pNotemgr->previewPoint);
}

void SceneMusicSelect::sceneFadeInEffect()
{
	auto layerSceneSwitchEffect = LayerColor::create(Color4B::BLACK);
	layerSceneSwitchEffect->setOpacity(255);
	addChild(layerSceneSwitchEffect, 65535);
	layerSceneSwitchEffect->runAction(
		Sequence::create(
			FadeTo::create(0.8f, 0),
			RemoveSelf::create(),
			NULL
		)
	);
}

void SceneMusicSelect::update(float dt)
{
}

void SceneMusicSelect::openSetting()
{
}

void SceneMusicSelect::gotoSoloScene()
{
	pNotemgr->hispeed = ((UICSliderBar*)msconsole->getChildByName("HI-SPEED"))->getValue();
	auto layerSceneSwitchEffect = LayerColor::create(Color4B::BLACK);
	layerSceneSwitchEffect->setOpacity(0);
	this->addChild(layerSceneSwitchEffect, 65535);
	layerSceneSwitchEffect->runAction(
		Sequence::create(
			FadeTo::create(0.2f, 255),
			CallFunc::create([&]
	{
		pAudioSystem->stopBGM();
		Director* director = Director::getInstance();
		pSceneFallingSolo = SceneFallingSingle::createScene();
		director->replaceScene(pSceneFallingSolo);
	}),
			NULL
		)
	);
}

void SceneMusicSelect::backtoMainmenu()
{
	sceneSwitchMode = random(0, 3);
	auto uiss = UISceneSwitcher::create(UISS_MODE(sceneSwitchMode), LEAVE);
	addChild(uiss);
	uiss->play();
	runAction(
		Sequence::create(
			DelayTime::create(1.5f),
			CallFunc::create([&]
	{
		Director* director = Director::getInstance();
		pSceneMainMenu = SceneMainMenu::createScene();
		director->replaceScene(pSceneMainMenu);
	}),
			NULL
		)
	);
}

void SceneMusicSelect::changeMusicSelect()
{
	if (mlist->selectedSetChanged)
	{
		auto setid = mlist->getItemByIndex(mlist->selectedindex)->setid;
		//loadMusicLevel();
		delete pNotemgr;
		pNotemgr = pDB->getMusicNoteBySetId(setid);
		string previewFile = pNotemgr->getPreviewFileName();
		if (!previewFile.empty())
			pAudioSystem->playBGMFadeIn(previewFile, 1000, VOLUMEMUSIC, pNotemgr->previewPoint);
		else
			pAudioSystem->stopBGM();
		mscover->changeCover(pNotemgr->bgFile);
		mlist->selectedSetChanged = false;
	}
	else
	{
		auto setid = mlist->selectedItem->setid;
		auto noteid = mlist->levelmgr->listdata[mlist->selectedLevelIndex].id;
		if (pNotemgr->setId != atoi(setid.c_str()) || pNotemgr->mapId != atoi(noteid.c_str()))
		{
			delete pNotemgr;
			pNotemgr = pDB->getMusicNoteBySetAndNoteId(setid, noteid);
		}

	}
	mapinfo->setInfoValue(mlist->levelmgr, mlist->selectedLevelIndex, pNotemgr);
}

//void SceneMusicSelect::loadMusicLevel()
//{
//	auto setitem = mlist->getItemByIndex(mlist->selectedindex);
//	auto setid = setitem->getName();
//	levelmgr.loadList(setid);
//}

void SceneMusicSelect::debugMsg()
{
}


